﻿using System;
using System.Security.Principal;
using System.Threading;
using MAF.Common;

namespace MAF.UserSecurity
{
    /// <summary>
    /// 安全操作
    /// </summary>
    public class UserContext : IPrincipal
    {
        #region 构造方法

        /// <summary>
        /// 构造方法，由Authenticator.Login方法调用此构造方法
        /// </summary>
        /// <param name="user"></param>
        internal UserContext(User user, DateTime expired)
        {
            Token = CombGuid.NewGuid();  // 生成Token

            Identity = user;
            User = user;
            Expired = expired;

            CreatedBy = Guid.Empty;
            CreatedOn = DateTime.Now;
            ModifiedBy = null;
            ModifiedOn = null;
        }
        
        /// <summary>
        /// 当前上下文
        /// 注意：如果此值一直为Null，则很可能是没有正确调用Authenticator.KeepLogon
        /// </summary>
        public static UserContext Current
        {
            get
            {
                var userContext = Thread.CurrentPrincipal as UserContext;
                if (null == userContext)
                {
                    // 创建一个未认证的用户
                    var user = new User();
                    user.Name = "过客";
                    userContext = new UserContext(user,DateTime.Now);   // TODO: 这里的Now可能会有问题
                }
                return userContext;
            }
        }

        #endregion

        #region IPrincipal 成员

        /// <summary>
        /// 用户标识
        /// </summary>
        public IIdentity Identity { get; private set; }

        /// <summary>
        /// 权限判断
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public bool IsInRole(string role)
        {
            if (null == Identity)
                return false;

            if (Identity.GetType() == typeof(User))
                return true;
            else
                return false;
        }

        #endregion

        /// <summary>
        /// 是否已经登录
        /// </summary>
        /// <returns></returns>
        public bool IsLogon
        {
            get
            {
                return User.IsAuthenticated;
            }
        }

        /// <summary>
        /// 令牌(本对象的Id)
        /// </summary>
        public Guid Token { get; private set; }

        /// <summary>
        /// 登陆关联的用户
        /// </summary>
        public User User { get; private set; }

        /// <summary>
        /// 过期
        /// </summary>
        public DateTime Expired { get; set; }

        #region 对象更新历史记录

        public Guid CreatedBy { get; set; }

        public Guid? ModifiedBy { get; set; }

        public DateTime CreatedOn { get; set; }

        public DateTime? ModifiedOn { get; set; }

        #endregion
    }
}